from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse, HttpRequest, JsonResponse
from django.http import HttpResponseBadRequest, HttpResponseNotFound

# from user.views import authenticate
from user.models import User
import simplejson
from user.views import  authenticate
from .models import Post, Content
import datetime
import math

@authenticate
def pub(request:HttpRequest):
    try:
        payload = simplejson.loads(request.body)
        print(payload)
        title = payload['title']
        author = request.user
        content = payload['content']

        post = Post()
        post.title = payload['title']
        post.author = request.user
        # post.pubdate = datetime.datetime.now(
        #     datetime.timezone(datetime.timedelta(hours=8)))
        post.pubdate = datetime.datetime.now()
        print(post.pubdate)
        post.save()

        content = Content()
        content.post = post
        content.content = payload['content']
        content.save()

        return JsonResponse(
            {
                "post_id": post.id
            }
        )

    except Exception as e:
        print(e)
        return HttpResponseBadRequest()

def get(request:HttpRequest, id):

    try:
        # post_id = int(id)
        post = Post.objects.get(pk = int(id))

        return JsonResponse(
            {
                'post': {
                    'post_id': post.id,
                    'title': post.title,
                    'postdate': post.pubdate,
                    'author': post.author.name,
                    'author_id': post.author_id,
                    'content': post.content.content
                },
            }
        )
    except Exception as e:
        print(e)
        return HttpResponseNotFound()

    # return HttpResponse(b'get')

def validate(d:dict, name:str, conv_func, default, val_func):
    try:
        ret = d.get(name)
        ret = conv_func(ret)
        ret = val_func(ret, default)
    except:
        ret = default
    return ret


def getall(request: HttpRequest):
    try:
        page = validate(request.GET, 'page', int, 1, lambda x, y : x if x > 0 else y)
        size = validate(request.GET, 'size', int, 20, lambda x, y :x if x > 0 and x <= 100 else y)
        print('page', page)
        print('size', size)

        start = (page - 1) * size

        # qs = Post.objects()

        count = Post.objects.count()
        print('count', count)
        posts = Post.objects.order_by('-id')[start:start + size]
        print('posts', posts)

        return JsonResponse({
            'posts': [
                {"post_id": post.id,
                "title": post.title } for post in posts ]
            ,
            'pagination': {
                'page': page,
                'size': size,
                'count': count,
                'pages': math.ceil(count / size)
            }
        })
    except Exception as e:
        print(e)
        return HttpResponseNotFound()


